package me.yuzho.study.concurrency.java8;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

/** 使用同步关键字synchronized来确保变量只被多根线程中的一根线程操作
 * @author yzhou-citrix
 *
 */
public class Case6Synchronized {
    
    private static final int NUM_INCREMENTS = 10000;
    
    private static int count = 0;

    private static void increment() {
        count = count + 1;
    }

    private static void testNonSyncIncrement() {
        
        count = 0;

        ExecutorService executor = Executors.newFixedThreadPool(2);

        IntStream.range(0, NUM_INCREMENTS)
                .forEach(i -> executor.submit(Case6Synchronized::increment));

        ConcurrentUtils.stop(executor);

        System.out.println("NonSync: " + count);
    }
    
    private static synchronized void incrementSync() {
        count = count + 1;
    }
    
    private static void testSyncIncrement() {
        
        count = 0;

        ExecutorService executor = Executors.newFixedThreadPool(2);

        IntStream.range(0, NUM_INCREMENTS)
                .forEach(i -> executor.submit(Case6Synchronized::incrementSync));

        ConcurrentUtils.stop(executor);

        System.out.println(" Sync: " + count);
    }

    public static void main(String[] args) {

        
        testNonSyncIncrement();
        testSyncIncrement();
        
    }

}
